package com.ruoyi.equ.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.regex.Pattern;

/**
 * 拼音工具类
 * 基于pinyin4j实现中文转拼音功能
 */
public class PinyinUtils {

    private static final Logger log = LoggerFactory.getLogger(PinyinUtils.class);

    // 中文正则表达式
    private static final Pattern CHINESE_PATTERN = Pattern.compile("[\\u4e00-\\u9fa5]");

    // 拼音输出格式配置
    private static final HanyuPinyinOutputFormat DEFAULT_FORMAT = new HanyuPinyinOutputFormat();

    static {
        // 设置输出格式
        DEFAULT_FORMAT.setCaseType(HanyuPinyinCaseType.UPPERCASE); // 大写
        DEFAULT_FORMAT.setToneType(HanyuPinyinToneType.WITHOUT_TONE); // 无声调
        DEFAULT_FORMAT.setVCharType(HanyuPinyinVCharType.WITH_V); // 使用v表示ü
    }

    /**
     * 获取中文字符串的首字母大写缩写
     *
     * @param chinese 中文字符串
     * @param maxLength 最大长度（默认2）
     * @return 首字母大写缩写，如"内科" -> "NK"
     */
    public static String getFirstLetterAbbr(String chinese, int maxLength) {
        if (chinese == null || chinese.trim().isEmpty()) {
            return "QT";
        }

        try {
            StringBuilder abbr = new StringBuilder();
            String cleaned = chinese.trim();

            for (int i = 0; i < cleaned.length() && abbr.length() < maxLength; i++) {
                char c = cleaned.charAt(i);

                if (isChinese(c)) {
                    // 中文转拼音首字母
                    String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, DEFAULT_FORMAT);
                    if (pinyinArray != null && pinyinArray.length > 0) {
                        abbr.append(pinyinArray[0].charAt(0));
                    }
                } else if (Character.isLetter(c)) {
                    // 英文字母直接取大写
                    abbr.append(Character.toUpperCase(c));
                }
                // 忽略其他字符（数字、符号等）
            }

            // 如果结果为空，返回默认值
            return abbr.length() > 0 ? abbr.toString() : "QT";

        } catch (BadHanyuPinyinOutputFormatCombination e) {
            log.error("拼音转换失败: {}", chinese, e);
            return getSimpleAbbr(chinese, maxLength);
        } catch (Exception e) {
            log.error("获取拼音缩写异常: {}", chinese, e);
            return getSimpleAbbr(chinese, maxLength);
        }
    }

    /**
     * 获取中文字符串的首字母大写缩写（默认最大长度2）
     */
    public static String getFirstLetterAbbr(String chinese) {
        return getFirstLetterAbbr(chinese, 2);
    }

    /**
     * 获取完整拼音（大写，无空格）
     *
     * @param chinese 中文字符串
     * @return 完整拼音，如"内科" -> "NEIKE"
     */
    public static String getFullPinyin(String chinese) {
        if (chinese == null || chinese.trim().isEmpty()) {
            return "";
        }

        try {
            StringBuilder pinyin = new StringBuilder();
            String cleaned = chinese.trim();

            for (int i = 0; i < cleaned.length(); i++) {
                char c = cleaned.charAt(i);

                if (isChinese(c)) {
                    String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, DEFAULT_FORMAT);
                    if (pinyinArray != null && pinyinArray.length > 0) {
                        pinyin.append(pinyinArray[0]);
                    }
                } else if (Character.isLetter(c)) {
                    pinyin.append(Character.toUpperCase(c));
                } else if (Character.isDigit(c)) {
                    pinyin.append(c);
                }
                // 忽略符号等特殊字符
            }

            return pinyin.toString();

        } catch (BadHanyuPinyinOutputFormatCombination e) {
            log.error("完整拼音转换失败: {}", chinese, e);
            return "";
        }
    }

    /**
     * 获取拼音首字母串（每个字的首字母）
     *
     * @param chinese 中文字符串
     * @return 拼音首字母串，如"中国人民解放军" -> "ZGRMJF"
     */
    public static String getPinyinInitials(String chinese) {
        if (chinese == null || chinese.trim().isEmpty()) {
            return "";
        }

        try {
            StringBuilder initials = new StringBuilder();
            String cleaned = chinese.trim();

            for (int i = 0; i < cleaned.length(); i++) {
                char c = cleaned.charAt(i);

                if (isChinese(c)) {
                    String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, DEFAULT_FORMAT);
                    if (pinyinArray != null && pinyinArray.length > 0) {
                        initials.append(pinyinArray[0].charAt(0));
                    }
                } else if (Character.isLetter(c)) {
                    initials.append(Character.toUpperCase(c));
                }
            }

            return initials.toString();

        } catch (BadHanyuPinyinOutputFormatCombination e) {
            log.error("拼音首字母转换失败: {}", chinese, e);
            return getSimpleAbbr(chinese, chinese.length());
        }
    }

    /**
     * 判断字符是否为中文
     */
    public static boolean isChinese(char c) {
        return CHINESE_PATTERN.matcher(String.valueOf(c)).matches();
    }

    /**
     * 判断字符串是否包含中文
     */
    public static boolean containsChinese(String str) {
        if (str == null || str.isEmpty()) {
            return false;
        }
        return CHINESE_PATTERN.matcher(str).find();
    }

    /**
     * 备用方案：简单的缩写生成（不使用拼音）
     */
    private static String getSimpleAbbr(String text, int maxLength) {
        if (text == null || text.trim().isEmpty()) {
            return "QT";
        }

        StringBuilder abbr = new StringBuilder();
        String cleaned = text.trim();

        for (int i = 0; i < cleaned.length() && abbr.length() < maxLength; i++) {
            char c = cleaned.charAt(i);
            if (Character.isLetter(c)) {
                abbr.append(Character.toUpperCase(c));
            } else if (isChinese(c)) {
                // 对于中文，如果拼音转换失败，取字符本身（作为备选）
                abbr.append(c);
            }
        }

        return abbr.length() > 0 ? abbr.toString() : "QT";
    }

    /**
     * 带预定义映射的科室缩写获取方法
     * 优先使用预定义映射，如果没有则使用拼音缩写
     */
    public static String getDeptAbbreviation(String deptName) {
        if (deptName == null || deptName.trim().isEmpty()) {
            return "QT";
        }

        // 预定义的科室缩写映射
        String predefinedAbbr = getPredefinedDeptAbbr(deptName.trim());
        if (predefinedAbbr != null) {
            return predefinedAbbr;
        }

        // 使用拼音首字母缩写
        return getFirstLetterAbbr(deptName, deptName.length());
    }

    /**
     * 预定义科室缩写映射
     */
    private static String getPredefinedDeptAbbr(String deptName) {
        switch (deptName) {
            case "内科": return "NK";
            case "外科": return "WK";
            case "儿科": return "EK";
            case "妇产科": return "FCK";
            case "骨科": return "GK";
            case "眼科": return "YK";
            case "耳鼻喉科": return "EBH";
            case "口腔科": return "KQK";
            case "皮肤科": return "PFK";
            case "神经科": return "SJK";
            case "心血管科": return "XXG";
            case "呼吸科": return "HXK";
            case "消化科": return "XHK";
            case "泌尿科": return "MNK";
            case "内分泌科": return "NFM";
            case "肿瘤科": return "ZLK";
            case "放射科": return "FSK";
            case "检验科": return "JYK";
            case "药剂科": return "YJK";
            case "急诊科": return "JZK";
            case "重症医学科": return "ZZY";
            case "康复科": return "KFK";
            case "中医科": return "ZYK";
            case "麻醉科": return "MZK";
            case "病理科": return "BLK";
            case "超声科": return "CSK";
            case "核医学科": return "HYX";
            case "输血科": return "SXK";
            case "营养科": return "YYK";
            case "感染科": return "GRK";
            case "预防保健科": return "YFB";
            case "设备科": return "SBK";
            case "后勤科": return "HQK";
            case "行政科": return "XZK";
            default: return null;
        }
    }

}
